<?php

/** An interface to the Hosting Reborn API account functions.
 * @package com\hostingreborn\api
 * @link https//api.hostingreborn.com/docs/functions/account/
 *
 * @author      Jon Cram <jon@hostingreborn.com>
 * @copyright   https://api.hostingreborn.com/code/copyright/
 * @license     https://api.hostingreborn.com/code/license/
 * @version     1.0
 *
 * $Date$
 * $Revision$
 *
 *
 */

require_once('HR_api.class.php');

class HR_accountApi extends HR_api {

    /***************************************************************************/
    /* Attributes                                                              */
    /***************************************************************************/


    /***************************************************************************/
    /* Constructors                                                            */
    /***************************************************************************/


    /***************************************************************************/
    /* Public methods                                                          */
    /***************************************************************************/


    /**
     * @link http://api.hostingreborn.com/docs/functions/key/get/
     *
     *
     * @param string $email
     * @param string $password
     * @return mixed string on success, otherwise false
     */
    public function getKey($email = '', $password = '') {
        /*
        Exceptions thrown by API:
            - database (handled internally by API)
            - system (handled internally by API)
        */

        $email = trim($email);
        $password = trim($password);

        if ($email == '' || $password == '') {
            return false;
        }

        $queryString = http_build_query(array(
                'email' => $email,
                'password' => $password
        ));

        return $this->read('key/get/?'.$queryString)->getValue('/key/key');
    }


    /**
     * @link http://api.hostingreborn.com/docs/functions/account/get/
     *
     *
     * @param string $key
     * @return array
     */
    public function get($key = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
        */

        $key = trim($key);
        if ($key == '') {
            return array(
                'email' => null,
                'status' => null,
                'balance' => null,
                'suspensionreason' => null
            );
        }

        $fullArgumentList = func_get_args();
        $queryString = $this->buildQueryString(array('key' => $key), $fullArgumentList);

        return $this->read('account/get/?'.$queryString)->getCollection(array(
                '/account/email' => 'email',
                '/account/status' => 'status',
                '/account/balance' => 'balance',
                '/account/suspensionreason' => 'suspensionreason'
        ));
    }




    /**
     * @link http://api.hostingreborn.com/docs/functions/account/get_balance/
     *
     * @param string $key
     * @param string $datetime Y-m-d H:i:s
     * @return float
     */
    public function getBalance($key = NULL, $datetime = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
        */

        $queryString = http_build_query(array(
                'key' => $key,
                'datetime' => $datetime
        ));

        return $this->read('account/get_balance/?'.$queryString)->getValue('/result/balance', 'float');
    }


    /**
     * @link http://api.hostingreborn.com/docs/functions/account/get_new_email/
     *
     * @param string $key
     * @return array
     */
    public function getNewEmail($key = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
        */

        $fullArgumentList = func_get_args();
        $queryString = $this->buildQueryString(array('key' => $key), $fullArgumentList);

        return $this->read('account/get_new_email/?'.$queryString)->getCollection(array(
                '/newemail/email' => 'email',
                '/newemail/status' => 'status'
        ));
    }


    /**
     * @link http://api.hostingreborn.com/docs/functions/account/cancel_new_email/
     *
     * @param string $key
     * @return boolean
     */
    public function cancelNewEmail($key = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
        */


        $arguments = array(
                'key' => $key
        );

        return $this->write('account/cancel_new_email/', $arguments)->wasSuccessful();
    }


    /**
     * @link http://api.hostingreborn.com/docs/functions/account/confirm_new_email/
     *
     * @param string $key
     * @param string $emailKey
     * @return boolean
     */
    public function confirmNewEmail($key = NULL, $emailKey = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
                - account
                  - 201: new email address taken
        */

        $arguments = array(
                'key' => $key,
                'email_key' => $emailKey
        );

        try {
            return $this->write('account/confirm_new_email/', $arguments)->wasSuccessful();
        } catch (HR_apiResponseUnhandledException $e) {
            $this->handleApiResponseUnhandledException($e);
        }
    }


    /**
     * @link http://api.hostingreborn.com/docs/functions/account/verify_email/
     *
     * @param string $email
     * @param string $key
     * @return boolean
     */
    public function verifyEmail($email = NULL, $key = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
        */

        $arguments = array(
                'email' => $email,
                'email_key' => $key
        );

        try {
            return $this->write('account/verify_email/', $arguments)->wasSuccessful();
        } catch (HR_apiResponseUnhandledException $e) {
            $this->handleApiResponseUnhandledException($e);
        }
    }


    /**
     * @link http://api.hostingreborn.com/docs/functions/account/get_notification_settings/
     *
     * @param string $key
     * @param string $email
     * @return array
     */
    public function getNotificationSettings($key = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
        */

        $fullArgumentList = func_get_args();
        $queryString = $this->buildQueryString(array('key' => $key), $fullArgumentList);

        $response = $this->read('account/get_notification_settings/?'.$queryString);

        $balanceWarningSettings = $response->getSet('/notificationsettings/balance/warning');
        $usageSummarySettings = $response->getSet('/notificationsettings/balance/summary');

        $usageAlerts['disk'] = $response->getSet('/notificationsettings/usagealerts/disk');
        $usageAlerts['bandwidth'] = $response->getSet('/notificationsettings/usagealerts/bandwidth');

        $settings['usageSummary'] = array();
        $settings['usageLimit'] = array();
        $settings['usageLimit'] = array();

        if (count($balanceWarningSettings)) {
            $settings['balanceWarningEnabled'] = $balanceWarningSettings[0]->getValue('/warning/enabled') == 'true';
            $settings['balanceWarningLevel'] = (int)$balanceWarningSettings[0]->getValue('/warning/level');
        }

        if (count($usageSummarySettings)) {
            foreach ($usageSummarySettings[0]->getSet('/summary/value') as $usageSummaryItem) {
                $settings['usageSummary'][$usageSummaryItem->getValue('/value')] = true;
            }
        }

        foreach ($usageAlerts as $type => $values) {
            if (count($values)) {
                foreach ($values[0]->getSet('/'.$type.'/value') as $usageSettingItem) {
                    $settings['usageLimit'][$type.$usageSettingItem->getValue('/value')] = true;
                }
            }
        }

        return $settings;
    }


    /**
     * @link http://api.hostingreborn.com/docs/functions/account/set_notification_settings/
     *
     * @param string $key
     * @param boolean $balanceWarning
     * @param float $balanceWarningLevel
     * @param boolean $summaryMonthly
     * @param boolean $summaryWeekly
     * @param boolean $summaryDaily
     * @param boolean $disk90
     * @param boolean $disk80
     * @param boolean $disk70
     * @param boolean $bandwidth90
     * @param boolean $bandwidth80
     * @param boolean $bandwidth70
     * @return boolean
     */
    public function setNotificationSettings($key = NULL, $balanceWarning = NULL, $balanceWarningLevel = NULL, $summaryMonthly = NULL, $summaryWeekly = NULL, $summaryDaily = NULL, $disk90 = NULL, $disk80 = NULL, $disk70 = NULL, $bandwidth90 = NULL, $bandwidth80 = NULL, $bandwidth70 = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
        */

        $arguments = array(
                'key' => $key,
                'balancewarning' => $balanceWarning,
                'balancewarninglevel' => $balanceWarningLevel*100,
                'monthlysummary' => $summaryMonthly,
                'weeklysummary' => $summaryWeekly,
                'dailysummary' => $summaryDaily,
                'disk90' => $disk90,
                'disk80' => $disk80,
                'disk70' => $disk70,
                'bandwidth90' => $bandwidth90,
                'bandwidth80' => $bandwidth80,
                'bandwidth70' => $bandwidth70
        );

        return $this->write('account/set_notification_settings/', $arguments)->wasSuccessful();
    }



    /**
     * @link http://api.hostingreborn.com/docs/functions/account/get_suspended_url/
     *
     * @param string $key
     * @return string
     */
    public function getSuspendedUrl($key = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
        */

        $queryString = http_build_query(array(
                'key' => $key
        ));

        return $this->read('account/get_suspended_url/?'.$queryString)->getValue('/url');
    }


    /**
     * @link http://api.hostingreborn.com/docs/functions/account/set_suspended_url/
     *
     * @param string $key
     * @param string $url
     * @return boolean
     */
    public function setSuspendedUrl($key = NULL, $url = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
        */

        $arguments = array(
                'key' => $key,
                'url' => $url
        );

        return $this->write('account/set_suspended_url/', $arguments)->wasSuccessful();
    }


    /**
     * @link http://api.hostingreborn.com/docs/functions/account/reset_password/
     *
     * @param string $email
     * @param string $password_key
     * @param string $new_password Optional, a secure password will be generated if omitted
     * @return mixed
     */
    public function resetPassword($email = NULL, $password_key = NULL, $new_password = NULL) {
        /*
            Exceptions thrown by API:
                - database (handled internally by API)
                - system (handled internally by API)
                - account
                  - 200: password reset failed
                  - 301: new password not sufficiently strong
        */

        $arguments = array(
                'email' => $email,
                'password_key' => $password_key,
                'new_password' => $new_password,
        );

        try {
            return $this->write('account/reset_password/', $arguments)->getValue('/password');
        } catch (HR_apiResponseUnhandledException $e) {
            $this->handleApiResponseUnhandledException($e);
        }
    }

    /***************************************************************************/
    /* Private methods                                                         */
    /***************************************************************************/


    /**
     *
     * @throws HR_apiAccountException
     * @param HR_apiResponseUnhandledException $exception
     */
    private function handleApiResponseUnhandledException(HR_apiResponseUnhandledException $exception) {
        if ($exception->getApiExceptionType() == 'account') {
            $code = null;

            switch ($exception->getApiExceptionCode()) {
                case '200':
                    $exceptionMessage = 'password reset failed';
                    break;

                case '201':
                case '203':
                    $exceptionMessage = 'email address already taken';
                    $code = 201;
                    break;

                case '301':
                    $exceptionMessage = 'new password not sufficiently strong';
                    $code = 202;
                    break;
            }

            throw new HR_apiAccountException($exceptionMessage, (is_null($code) ? $exception->getApiExceptionCode() : $code));
        }
    }


}

?>